<template>
  <div class="login">
    <div class="bg-icon"></div>
    <div class="logo"><img src="../../assets/jb/logo2.png"></div>
    <div class="Hello">{{$t('Hello')}}</div>
    <div class="adLanguage">{{$t('corporate')}}</div>
    <div class="nationalFlag"  @click="show = true">
      <i></i>
      {{$t('nationalFlag')}}
    </div>
    <van-popup v-model="show" closeable position="bottom" :style="{ height: '30%' }">
        <van-cell-group>
        <van-cell v-for="(item, index) in langs"
                  :key="item"
                  @click="changeFn(index)">
          <span>{{ item }}</span>
          <van-icon v-if="locale === index"
                    name="success"
                    color="@themeColor" />
        </van-cell>
      </van-cell-group>
    </van-popup>
    
    <div class="form-row">
      <div class="tab">
        <ul>
          <li v-for="(item,index) in tab" :key="index" @click="active = item.active" :class="active===item.active?'current':''">{{ item.lable }}</li>
        </ul>
      </div>
      <van-form v-if="active === 1" label-width="4em" @submit="onSubmit" >
        <van-field v-model="username" :rules="[{ required: true }]">
          <div slot="label" class="slot-label">
            <select v-model="loginType" class="select">
              <option value="phone">{{ $t('pageSign.phone') }}</option>
              <option value="email">{{ $t('pageSign.email') }}</option>
            </select>
          </div>
          <div v-if="loginType === 'email'" slot="input" class="slot-inp">
            <input v-model="username" type="text" class="van-field__control" :placeholder="$t('pageSign.email')" />
          </div>
          <div v-if="loginType === 'phone'" slot="input" class="slot-inp">
            <span class="tel-area" @click="showPicker=true">{{ area_num }} -</span>
            <input v-model="username" type="number" class="van-field__control" :placeholder="$t('pageSign.phone')" />
          </div>
        </van-field>
        <van-field v-model="password" type="password" :placeholder="$t('pageSign.pleaseEnterThePwd')" :rules="[{ required: true }]">
        </van-field>
        <van-button block type="info" native-type="submit" class="submit">{{ $t('login') }}</van-button>
        <van-checkbox v-model="checked">{{$t('signinAndAgree')}}<p @click="open = true">《{{$t('userAgreement')}}》</p>
        </van-checkbox>

      </van-form>

      <van-form v-else label-width="4em" @submit="onSubmit">
        <van-field v-model="username" :rules="[{ required: true }]">
          <div slot="label" class="slot-label">
            <select v-model="loginType" class="select">
              <option value="phone">{{ $t('pageSign.phone') }}</option>
              <option value="email">{{ $t('pageSign.email') }}</option>
            </select>
          </div>
          <div v-if="loginType === 'email'" slot="input" class="slot-inp">
            <input v-model="username" type="text" class="van-field__control" :placeholder="$t('pageSign.email')" />
          </div>
          <div v-if="loginType === 'phone'" slot="input" class="slot-inp">
            <span class="tel-area" @click="showPicker=true">{{ area_num }} -</span>
           <input v-model="username" type="number" class="van-field__control" :placeholder="$t('pageSign.phone')" />
        </div>
        </van-field>
        <van-field v-model="verification_code" clearable :placeholder="$t('pageSign.pleaseEnterTheCode')" :rules="[{ required: true }]">
          <template v-if="active === 2" #button>
            <van-button size="small" type="primary" block :disabled="times !== 60" @click.prevent="handleGetCode" >
              <template v-if="times === 60">{{ $t('pageSign.send_code') }}</template>
              <template v-else>{{ times }}s</template>
            </van-button>
          </template>
        </van-field>
        <van-button block type="info" native-type="submit" class="submit"> {{ $t('login') }} </van-button>
        <van-checkbox v-model="checked">{{$t('signinAndAgree')}}<p @click="open = true">《{{$t('userAgreement')}}》</p>
        </van-checkbox>
      </van-form>
      <div class="links">
          <nuxt-link to="/sign/register">{{ $t('pageSign.free_reg') }}</nuxt-link>
          <nuxt-link to="/sign/forget">{{ $t('pageSign.forget_pwd') }}</nuxt-link>
        </div>
    </div>
    <van-popup v-model="open" position="bottom" closeable round :style="{ height: '70%' }">
      <div class="notice" v-html="$t('agreement')"></div>
    </van-popup>
    <van-popup v-model="showPicker" position="bottom" round>
      <van-picker show-toolbar :columns="areaNums" :visible-item-count="10" @confirm="confirmArea" @cancel="showPicker=false" />
    </van-popup>
    <div class="max-bg">
    </div>
    <div class="min-bg"></div>
  </div>
</template>
<script>
import { mapState,mapActions } from 'vuex'
import { areaNums } from '@/constants/area_nums'
export default {
  i18n: {
    messages: {
      zh: {
        nationalFlag:"语言选择",
        Hello:"您好",
        corporate:"欢迎开启智能AI量化财富时代",
        signinAndAgree:"登录注册表示同意",
        userAgreement:"用户隐私及协议条款",
        agreement:`<div class="noticeName">AISS用户风险告知</div><p>（请您务必仔细阅读并收藏）感谢您选择AISS智能服务软件，在您使用或尝试使用AISS服务时，请您认真阅读AISS“用户使用协议”，同时针对使用的相关风险告知如下：</p><p><span>1.</span>二级市场变幻莫测，只要是投资都不可能100%无风险；</p><p><span>2.</span>数字资产的价值可能会出现大幅波动，数字资产买卖和数字资产持有存在巨大的风险，也有可能会在买卖和持有数字资产时产生经济损失；</p><p><span>3.</span>使用AISS虽然可以通过分散投资降低风险，但并不代表没有风险；</p><p><span>4.</span>根据自身的经济情况选择合适的策略数量，合理控制风险；</p><p><span>5.</span>受市场行情影响，存在没有收益或者亏损的可能性；</p><p><span>6.</span>AISS不设资金池，不作保本承诺，不作保底收益承诺，不承担亏损风险，不承担投资风险；</p><p><span>7.</span>由于市场行情及技术等其他不可抗力的因素，它提供的服务也有可能存在没有收益和亏损的可能性；</p><p><span>8.</span>当您使用AISS的服务时，将视同您已经拥有担承风险的能力且了解并愿意承担相关亏损风险。</p><p class="weight">投资有风险，选择需谨慎！以上风险告知请广大会员认真阅读！</p>`,
      },
      en: {
        nationalFlag:"language selection",
        Hello:"Hello!",
        corporate:"Welcome to the era of intelligent AI quantitative wealth",
        signinAndAgree:"Sign in and agree",
        userAgreement:"User privacy and agreement terms",
        agreement:`<div class="noticeName">AISS user risk notification</div><p>(Please read it carefully and save it)Thank you for choosing the AISS intelligent service software.When you use or try to use the AISS service,please read the AISS"User Agreement"carefully,and at the same time inform the related risks of use as follows:</p><p><span>1.</span>The secondary market is unpredictable,as long as it is an investment,it is impossible to be 100%risk-free;</p><p><span>2.</span>The value of digital assets may fluctuate sharply.There are huge risks in digital asset buying and selling and digital asset holding,and there may also be economic losses when buying,selling and holding digital assets;</p><p><span>3.</span>Although the use of AISS can reduce risk by diversifying investment,it does not mean that there is no risk;</p><p><span>4.</span>Choose an appropriate number of strategies according to your own economic situation,and reasonably control risks;</p><p><span>5.</span>Affected by market conditions,there is the possibility of no gain or loss;</p><p><span>6.</span>AISS does not set up a capital pool,does not make a guarantee of capital,does not make a promise of guaranteed return,does not bear the risk of loss,and does not bear the risk of investment;</p><p><span>7.</span>Due to other force majeure factors such as market conditions and technology,the services it provides may also have the possibility of no gain or loss;</p><p><span>8.</span>When you use AISS's services,you will be deemed to have the ability to bear risks and understand and are willing to bear the related risk of loss.</p><p class="weight">Investment is risky,so choose carefully!Please read the above risk notice carefully!</p>`,
      },
      jp: {
        nationalFlag:"言語選択",
        Hello:"こんにちは",
        corporate:"知能AIを開いて財産の時代を定量化することを歓迎します。",
        signinAndAgree:"ログインに同意します。",
        userAgreement:"ユーザープライバシーと協議条項",
        agreement:`<div class="noticeName">AISSユーザーリスク通知</div><p>（必ずよくお読みになり、保存してください）AISSインテリジェントサービスソフトウェアをお選びいただきありがとうございます。AISSサービスをご利用またはご利用になる際は、AISS「ユーザー規約」をよくお読みになり、使用上のリスクをお知らせください。次のように：</p><p><span>1.</span>流通市場は、それが投資である限り、100％リスクフリーになることは不可能であるため、予測不可能です。</p><p><span>2.</span>デジタル資産の価値は大きく変動する可能性があります。デジタル資産の売買には大きなリスクがあり、デジタル資産の売買や保有には経済的損失が生じる可能性があります。</p><p><span>3.</span>AISSを使用すると、投資を分散することでリスクを軽減できますが、リスクがないという意味ではありません。</p><p><span>4.</span>自分の経済状況に応じて適切な数の戦略を選択し、リスクを合理的に管理します。</p><p><span>5.</span>市況の影響を受け、損益が発生しない可能性があります。</p><p><span>6.</span>AISSは、ファンドプールを設定せず、資本を保証せず、保証されたリターンを約束せず、損失のリスクを負わず、投資のリスクを負いません。</p><p><span>7.</span>市況や技術などの他の不可抗力要因により、それが提供するサービスにも利益と損失がない可能性があります。</p><p><span>8.</span>AISSのサービスを利用する場合、リスクを負い、関連する損失のリスクを理解し、負担する意思があると見なされます。</p><p class="weight">投資にはリスクが伴いますので、慎重に選択してください。上記のリスク通知を注意深くお読みください！</p>`,
      },
      kr: {
        nationalFlag:"언어 선택",
        Hello:"안녕하세요",
        corporate:"부의 지능형 AI 정량화 시대에 오신 것을 환영합니다.",
        signinAndAgree:"동의하려면 로그인하고 가입하세요.",
        userAgreement:"사용자 개인 정보 및 계약 조건",
        agreement:`<div class="noticeName">AISS 사용자 위험 알림</div><p>(잘 읽어보시고 저장해 주세요) AISS 지능형 서비스 소프트웨어를 선택해 주셔서 감사합니다. AISS "이용약관"과 동시에 다음과 같이 관련 사용상의 위험성을 알려드립니다.</p><p><span>1.</span> 2차 시장은 투자인 한 예측할 수 없으며, 100% 위험이 없는 것은 불가능합니다. </p><p><span>2.</span> 디지털 자산의 가치는 크게 변동할 수 있습니다. 디지털 자산을 사고 팔고 보유하는 데는 큰 위험이 있습니다. , 그리고 디지털 자산을 사고 팔고 보유할 때도 위험이 있을 수 있습니다. 경제적 손실이 발생합니다.</p><p><span>3.</span> AISS를 사용하면 투자를 분산하여 위험을 줄일 수 있지만, 위험이 없다는 의미는 아닙니다.</p><p><span>4.</span>자신의 경제 상황에 따라 적절한 수의 전략을 선택하고 위험을 합리적으로 제어합니다.</p><p><span >5.</span>시장 상황의 영향을 받아 손익의 가능성이 없습니다.</p><p><span>5.</span> p><p><span>6.</p> span> AISS는 펀드 풀을 설정하지 않고, 자본을 보증하지 않으며, 보장된 수익을 약속하지 않으며, 손실 위험을 부담하지 않으며, 투자 위험을 부담하지 않습니다.</p>< p><span>7 .</span> 시장 상황 및 기술과 같은 기타 불가항력 요인으로 인해 서비스가 제공하는 서비스에도 이익 또는 손실이 없을 가능성이 있습니다.</p><p><span>8 .</span> 이용 시 AISS가 서비스를 제공할 때, 귀하는 이미 위험을 감수할 능력이 있고 관련 손실 위험을 이해하고 감수할 의향이 있는 것으로 간주됩니다. </p><p class="weight">투자는 위험하므로 신중하게 선택하십시오! 위의 위험 고지를 주의 깊게 읽으십시오! </p>`,
      }
    }
  },
  data () {
    return {
      show:false,
      langs: {
        zh: '中文',
        en: 'English',
        jp: '日本語',
        kr: '한국어'
      },
      tab: [
        {
          lable: this.$t('pageSign.login_pwd'),
          active: 1
        },
        {
          lable: this.$t('pageSign.login_code'),
          active: 2
        }
      ],
      areaNums,
      logo: require('@/assets/images/login_logo.png'),
      active: 1,
      username: '',
      password: '',
      verification_code: '',
      times: 60,
      loginType: 'phone',
      area_num: '86',
      showPicker: false,
      checked:false,
      open:false
    }
  },
  computed: {
    ...mapState({
      locale: state => state.locale
    })
  },
  methods: {
    changeFn(index){
      this.$i18n.locale = index
      this.setLang(index)
    },
    ...mapActions({
      setLang: 'setLang',
      getCode: 'user/getCode',
      login: 'user/login'
    }),

    handleGetCode () {
      const username = this.loginType === 'phone' ? `${this.area_num}-${this.username}` : this.username
      this.$toast.loading()
      this.getCode(username)
        .then(({ msg }) => {
          this.$toast(msg)
          this.getTime()
        })
        .catch(({ msg }) => {
          this.$toast(msg)
        })
    },
    onSubmit () {
      if(!this.checked){
        this.$toast('请勾选阅读用户隐私及协议条款')
        return
      }
      this.$toast.loading()
      const username = this.loginType === 'phone' ? `${this.area_num}-${this.username}` : this.username
      const payload = { username, device_type: 'web' }
      if (this.active === 1) {
        payload.password = this.password
      } else {
        payload.verification_code = this.verification_code
      }
      this.$toast.loading()
      this.login([this.active, payload])
        .then((res) => {
          this.$toast(res.msg)
          this.$nextTick(() => {
            this.$router.replace('/home')
          })
        })
        .catch((res) => {
          this.$toast(res.msg)
        })
    },
    getTime () {
      this.timer = setInterval(() => {
        this.times--
        if (this.times === 0) {
          clearInterval(this.timer)
          this.times = 60
        }
      }, 1000)
    },
    confirmArea (values) {
      this.area_num = values.phone_code
      this.showPicker = false

    }
  }
}
</script>
<style lang="less" scoped>
.nationalFlag{
  position: absolute;
  right: 20px;
  top:20px;
  font-size: 12px;
  color: #ffffff;
  display: flex;
  align-items: center;
  i{
    margin-right: 3px;
    display: block;
    width: 25px;
    height: 25px;
    background: url("./icon/yuyan.png") no-repeat;
    background-size: 20px 20px;
    background-position: center;
  }
}
.login{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    padding: 24px;
    line-height: 1;
    min-height: 100%;
    overflow: hidden;
    box-sizing: border-box;
    background: linear-gradient(139deg, #203FFF 0%, #00B8FF 100%);
    .bg-icon{
        position: absolute;
        top: 97px;
        right: -124px;
        width: 341px;
        height: 362px;
        border-radius: 50%;
        background: linear-gradient(180deg, #FFFFFF 0%, rgba(255, 255, 255, 0.37) 100%);
        opacity: 0.18;
    }
    .max-bg{
      position: absolute;
      bottom: -150px;
      left: -150px;
      width: 300px;
      height: 300px;
      box-sizing: border-box;
      border-radius: 50%;
      background: linear-gradient(180deg, #FFFFFF 0%, rgba(255, 255, 255, 0.37) 100%);
      opacity: 0.1;
    }
    .min-bg{
      position: absolute;
      bottom: -100px;
      left: -100px;
      width: 180px;
      height: 180px;
      border-radius: 50%;
      background: linear-gradient(180deg, #FFFFFF 0%, rgba(255, 255, 255, 0.37) 100%);
      opacity: 0.09;
    }
  .logo{
    margin-top: 45px;
    padding: 0;
    width: 58px;
    height: 58px;
    display: block;
    border-radius: 50%;
    background: #FFFFFF;
    border: 1px solid #ffffff;
    img{
      width: 56px;
      height: 56px;
      display: block;
    }
  }
  .Hello{
    padding: 18px 0 12px 0;
    font-size: 41px;
    font-weight: 400;
    color: #FFFFFF;
  }
  .adLanguage{
    font-size: 19px;
    font-weight: 400;
    color: #FFFFFF;
    line-height: 26px;
  }
  .form-row{
    position: relative;
    margin-top: 45px;
    background: #FFFFFF;
    border-radius: 28px;
    z-index: 1;
    .tab{
      padding: 13px 8px 0 8px;
      ul{
        display: flex;
         border-bottom: #EBEBEB solid 1px;
        li{
          position: relative;
          flex: 1;
          height: 45px;
          line-height: 45px;
          font-size: 15px;
          color: #999999;
          text-align: center;
          &.current{
            color: #366FF9;
            &:after{
              position: absolute;
              bottom: 0;
              left: 0;
              right: 0;
              margin: 0 auto;
              content:"";
              width: 30px;
              height: 3px;
              background: #366FF9;
              border-radius: 2px;
            }
          }
        }
      }
    }
    .van-form{
      padding: 22px 30px;
      /deep/.van-cell__title{
        margin-right: 5px;
      }
      /deep/.van-field__label{
        width: auto;
        display: flex;
        align-items: center;
        .select{
          font-size: 14px;
          width: auto;
          background: transparent;
          border: none;
        }
        .van-icon{
          font-size: 14px;
        }
      }
      .van-field{
        position: relative;
        margin-top: 24px;
        padding: 0;
        &:after{
          left: 0;
          right: 0;
          border-bottom: 1px solid #4CCBF2;
        }
        /deep/input{
          height: 34px;
          font-size: 16px;
          font-weight: 400;
        }
        .slot-inp{
          display: flex;
          .tel-area{
            flex: 30px 0 0;
          }
        }
        /deep/.van-field__button{
          position: absolute;
          right: 0;
          bottom: -0px;
          padding: 0 0 0 13px;
          background: #ffffff;
          z-index: 1;
          .van-button{
            width: 96px;
            height: 30px;
            font-size: 12px;
            font-weight: 500;
            color: #4CCBF2;
            border-radius: 16px;
            background: transparent;
            border: 1px solid #4CCBF2;
          }
        }
      }
      .submit{
        margin-top: 30px;
        height: 48px;
        font-size: 20px;
        font-weight: 500;
        color: #FFFFFF;
        background: linear-gradient(137deg, #91E2FF 0%, #0B6CFF 100%);
        border-radius: 26px;
        border: none;
      }
      .van-checkbox{
        margin-top: 10px;
        /deep/.van-checkbox__icon {
          height: 12px;
          .van-icon{
            height: 12px;
            width: 12px;
            font-size: 10px;
            &:before{
              font-size: 10px;
            }
          }
        }
        /deep/.van-checkbox__label{
          margin-left: 2px;
          font-size: 11px;
          font-weight: 400;
          color: rgba(155, 155, 155, 0.49);
          p{
            display: inline-block;
            color: #079EFF;
          }
        }
      }
    }
    .links{
        display: flex;
        text-align: center;
        padding: 20px 0 24px 0;
        a{
          flex: 1;
          font-size: 12px;
          font-weight: 400;
          color: #079EFF;
          &:last-child{
            border-left: 1px solid #F1F1F1;
          }
        }
      }
  }
}
/deep/.notice{
  padding: 10px 20px;
  .noticeName{
    font-size: 18px;
    text-align: center;
    padding: 10px 0 20px 0;
    font-weight: bold;
    color: #000000;
  }
  p{
    font-size: 13px;
    line-height: 20px;
    color: #333333;
    display: flex;
    &.weight{
      padding: 10px 0 0 0;
      font-size: 13px;
      font-weight: bold;
      color: #000000;
    }
  }
}
</style>
